<script setup lang="ts">
import { processAssistantMessage, renderMarkdown } from "@/utils";

interface Message {
  role: string;
  content: string;
  id: string;
  isGenerating: boolean;
  isLoading: boolean;
}

const props = defineProps<{
  message: Message;
}>();

const messageParts = computed(() =>
  processAssistantMessage(props.message.content)
);
// 判断是否是代码块且正在加载
const isCodeLoading = (part: any) => {
  return part.type === "code" && props.message.isGenerating;
};
</script>

<template>
  <div class="message-container">
    <template v-for="(part, index) in messageParts" :key="index">
      <!-- 普通文本部分，走 markdown 渲染 -->
      <div
        v-if="part.type === 'text'"
        class="text-part"
        v-html="renderMarkdown(part.content)"
      ></div>

      <!-- 代码块部分 -->
      <CodeBlock
        v-else
        :code="part.content"
        :language="part.language"
        :isLoading="isCodeLoading(part)"
      />
    </template>
  </div>
</template>

<style scoped lang="scss">
.message-container {
  line-height: 1.5;
  &:deep(h3) {
    line-height: 1.5;
    font-size: calc(1.143 * 16px);
    margin: calc(1.143 * 16px) 0 calc(1.143 * 12px) 0;
  }
  &:deep(h1):first-child {
    margin-top: 0;
  }
  &:deep(ul),
  &:deep(ol) {
    padding-left: calc(1.143 * 24px);
    margin: calc(1.143 * 12px) 0;
  }
  &:deep(p):last-child {
    margin-bottom: 0;
  }
  &:deep(p):first-child {
    margin-top: 0;
  }
  &:deep(table) {
    text-align: left;
    border-collapse: collapse;
    th {
      border-bottom: 1px solid rgb(163, 163, 163);
      font-weight: 600;
      color: rgb(64, 64, 64);
      border-color: #bbb;
    }
    td {
      border-bottom: 1px solid rgb(229, 229, 229);
    }
    th,
    td {
      padding: 10px;
      font-size: 15px;
      line-height: 1.72;
      &:first-child {
        padding-left: 0;
      }
    }
  }
  &:deep(code) {
    background: #ececec;
    padding: 0.15rem 0.3rem;
    margin: 0 0.3em;
    border-radius: 3px;
    font-size: 0.9em;
    font-family: Inter, "Helvetica Neue", Helvetica, "PingFang SC",
      "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  }
  .text-part {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    min-height: 35px;
  }
}
</style>
